import React, { PropsWithChildren, useEffect, useState } from "react";
import { connect } from "react-redux";
import { CombinedState } from "../../store/reducers";
import { ProfileState } from "../../store/reducers/profile";
import actions from "../../store/actions/profile";
import LOGIN_TYPES from "../../typings/login-types";
import { RouteComponentProps } from "react-router";
import { Descriptions, Button, Alert, message, Upload } from "antd";
import { LoadingOutlined, UploadOutlined } from "@ant-design/icons";
import NavHeader from "../../components/NavHeader";
import { AxiosError } from "axios";
import "./index.less";
//当前的组件有三个属性来源
//1.mapStateToProps的返回值 2.actions对象类型 3. 来自路由 4.用户传入进来的其它属性

type StateProps = ReturnType<typeof mapStateToProps>
type DispatchProps = typeof actions


interface Params { }
type RouteProps = RouteComponentProps<Params>
type Props = PropsWithChildren<StateProps & DispatchProps & RouteProps>
function Profile(props: Props) {
    console.log('props', props)
    let [loading, setLoading] = useState(false)
    //组件加载后直接 发起验证请求,查看此用户是否已经登录过了,如果没有登录则提示错误
    useEffect(() => {
        props.validate().catch((error: AxiosError) => message.error(error.message))
    }, []);
    const handleChange = (info: any) => {
        if (info.file.status === 'uploading') {
            setLoading(true)
        } else if (info.file.status === 'done') {
            let { success, data, message } = info.file.response
            if (success) {
                setLoading(false)
                props.changeAvatar(data)
            } else {
                message.error(message)
            }
        }
    }
    let content // 存放需要渲染的内容
    if (props.loginState == LOGIN_TYPES.UN_VALIDATE) {
        content = null
    } else if (props.loginState == LOGIN_TYPES.LOGINED) {
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <UploadOutlined />}
                <div className="ant-upload-text">上传</div>
            </div>
        )
        content = (
            <div className="user-info">
                <Descriptions title="当前登录用户">
                    <Descriptions.Item label="用户名">{props.user.username}</Descriptions.Item>
                    <Descriptions.Item label="邮箱">{props.user.email}</Descriptions.Item>
                    <Descriptions.Item label="邮箱">
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://localhost:8000/user/uploadAvatar"
                            beforeUpload={beforeUpload}
                            data={{ userId: props.user.id }}
                            onChange={handleChange}
                        >
                            {props.user.avatar ? (
                                <img src={props.user.avatar} alt="avatar" style={{ width: '100%' }}></img>
                            ) : uploadButton}
                        </Upload>
                    </Descriptions.Item>
                </Descriptions>
                <Button type="primary" onClick={async () => {
                    await props.logout()
                    props.history.push('/login')
                }}>退出登录</Button>
            </div>
        )
    } else {
        content = (
            <>
                <Alert
                    type="warning"
                    message="当前未登录"
                    description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录"
                />
                <div style={{ textAlign: "center", padding: "50px" }}>
                    <Button type="dashed" onClick={() => props.history.push("/login")}>
                        登录
                    </Button>
                    <Button
                        type="dashed"
                        style={{ marginLeft: "50px" }}
                        onClick={() => props.history.push("/register")}
                    >
                        注册
                    </Button>
                </div>
            </>
        )
    }
    return (
        <div>
            <section>
                <NavHeader history={props.history}>个人中心</NavHeader>
                {content}
            </section>
        </div>
    )
}
let mapStateToProps = (initialState: CombinedState): ProfileState => initialState.profile;
export default connect(mapStateToProps, actions)(Profile);

function beforeUpload(file: any) {
    const isJpgOrPnG = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPnG) message.error('Only support for JPG/PNG to upload')
    const isLessThan2m = file.size / 1024 / 1024 < 2
    if (!isLessThan2m) message.error('The file must be less than 2MB!')
    return isJpgOrPnG && isLessThan2m
}